package bma.common.langutil.concurrent;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

public class ExternalManagedExecutorService implements ExecutorService {

	protected ExecutorService service;
	protected AtomicBoolean shutdown = new AtomicBoolean();

	public ExternalManagedExecutorService() {
		super();
	}

	public ExternalManagedExecutorService(ExecutorService service) {
		super();
		this.service = service;
	}

	@Override
	public void execute(Runnable command) {
		this.service.execute(command);
	}

	@Override
	public void shutdown() {
		shutdown.set(true);
	}

	@Override
	public List<Runnable> shutdownNow() {
		shutdown.set(true);
		return Collections.emptyList();
	}

	@Override
	public boolean isShutdown() {
		return shutdown.get() || service.isShutdown();
	}

	@Override
	public boolean isTerminated() {
		return shutdown.get() || service.isTerminated();
	}

	@Override
	public boolean awaitTermination(long timeout, TimeUnit unit)
			throws InterruptedException {
		return isTerminated();
	}

	@Override
	public <T> Future<T> submit(Callable<T> task) {
		return this.service.submit(task);
	}

	@Override
	public <T> Future<T> submit(Runnable task, T result) {
		return this.service.submit(task, result);
	}

	@Override
	public Future<?> submit(Runnable task) {
		return this.service.submit(task);
	}

	@Override
	public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
			throws InterruptedException {
		return this.service.invokeAll(tasks);
	}

	@Override
	public <T> List<Future<T>> invokeAll(
			Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
			throws InterruptedException {
		return this.service.invokeAll(tasks, timeout, unit);
	}

	@Override
	public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
			throws InterruptedException, ExecutionException {
		return this.service.invokeAny(tasks);
	}

	@Override
	public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
			long timeout, TimeUnit unit) throws InterruptedException,
			ExecutionException, TimeoutException {
		return this.service.invokeAny(tasks, timeout, unit);
	}

}
